<script setup lang="tsx">
import { getRoleListApi, deleteRoleApi } from '@/api/role'
import Write from './components/Write.vue'
import Permission from './components/Permission.vue'
import { ElButton } from 'element-plus'
import { FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { TableColumn } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'

const { t } = useI18n()

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getRoleListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await deleteRoleApi(unref(ids.value[0]))
    return !!res
  }
})

const { dataList, loading, total, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'name',
    label: t('role.roleName')
  },
  {
    field: 'remark',
    label: t('userDemo.remark')
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 160,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <ElButton
              v-hasPermi="POST /role/update"
              type="primary"
              link
              onClick={() => action(row, 'edit')}
            >
              {t('exampleDemo.edit')}
            </ElButton>
            <ElButton
              v-hasPermi="GET /role/permissions"
              type="success"
              link
              onClick={() => setPermission(row)}
            >
              {t('role.permission')}
            </ElButton>
            <ElButton
              v-hasPermi="POST /role/delete/{id}"
              type="danger"
              link
              onClick={() => delData(row)}
            >
              {t('exampleDemo.del')}
            </ElButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: t('role.roleName'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  currentPage.value = 1
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const permissionDialogVisible = ref(false)

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t('exampleDemo.edit')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const delLoading = ref(false)

const delData = async (row: any) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: any) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const setPermission = (row: any) => {
  dialogTitle.value = t('role.permissionConfig')
  currentRow.value = row
  permissionDialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  saveLoading.value = true
  const write = unref(writeRef)
  const res = await write?.submit()
  saveLoading.value = false
  if (!res) {
    return
  }
  dialogVisible.value = false
  getList() // 刷新列表
}

const permissionRef = ref<ComponentRef<typeof Permission>>()

const updatePermission = async () => {
  saveLoading.value = true
  const permission = unref(permissionRef)
  const res = await permission?.submit()
  saveLoading.value = false
  if (!res) {
    return
  }
  permissionDialogVisible.value = false
  getList() // 刷新列表
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <ElButton v-hasPermi="'POST /role/create'" type="primary" @click="AddAction">{{
        t('exampleDemo.add')
      }}</ElButton>
    </div>
    <Table
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" :maxHeight="100">
    <Write ref="writeRef" :current-row="currentRow" />

    <template #footer>
      <ElButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
  <Dialog v-model="permissionDialogVisible" :title="dialogTitle">
    <Permission ref="permissionRef" :current-row="currentRow" />
    <template #footer>
      <ElButton type="primary" :loading="saveLoading" @click="updatePermission">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="permissionDialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
